package com.open.party.cloud.view.home.jiCengDangJian

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.android.x.model.data.ResultInfo
import cn.android.x.parent.AppEventBusTitleBaseActivity
import cn.android.x.utils.PhoneUtil
import cn.sinothk.hussars.map.PoiSelectMapViewActivity
import cn.sinothk.map.amap.navigate.AMapNavi
import com.alibaba.fastjson.JSON
import com.bumptech.glide.Glide
import com.jiangyy.easydialog.SingleChoiceDialog
import com.open.party.cloud.R
import com.open.party.cloud.ServerConfig
import com.open.party.cloud.model.TownshipBean
import com.open.party.cloud.model.TownshipVo
import com.open.party.cloud.model.data.CodeValue
import com.open.party.cloud.model.data.LocalCache
import com.open.party.cloud.view.base.ImageShowAdapter
import com.open.party.cloud.view.comm.data.Constants
import com.open.party.cloud.view.login.LoginActivity
import com.open.party.cloud.viewModel.OrgViewModel
import com.sinothk.android.utils.XUtils
import com.sinothk.image.selector.PhotoPreviewActivity
import com.sinothk.video.core.DataUtils
import com.sinothk.video.core.bean.VideoSourceEntity
import com.sinothk.video.show.VideoPlaySingleActivity
//import com.sinothk.map.amap.navigate.MapUtil
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.android.synthetic.main.jcdj_community_detail.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.ByteArrayOutputStream

class OrgCountryDetailsActivity : AppEventBusTitleBaseActivity() {
    private var viewModel: OrgViewModel? = null
    private var townshipBean: TownshipBean? = null

    override fun getLayoutResId(): Int = R.layout.jcdj_community_detail

    private fun shareToWx(township: TownshipBean) {
        SingleChoiceDialog.Builder(this).setTitle("信息分享")
            .addList(arrayOf("分享到朋友圈", "分享给微信好友"))
            .setOnItemClickListener { title, _ ->

                val titleStr = XUtils.string().getNotNullValue(township.name)
                val descStr = XUtils.string().getNotNullValue(township.address)
                val url = ServerConfig.getArticleUrl(township.id)

                val scene = if (title == "分享给微信好友") {
                    SendMessageToWX.Req.WXSceneSession
                } else {
                    SendMessageToWX.Req.WXSceneTimeline
                }
                shareWebPage(titleStr, descStr, url, scene)
            }.show()
    }

    //    private var api: IWXAPI? = null
    private fun shareWebPage(title: String, desc: String, url: String, scene: Int) {

        val api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false)

        //初始化一个WXWebpageObject，填写url
        val webpage = WXWebpageObject()
        webpage.webpageUrl = url    //"https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Share_and_Favorites/Android.html"

        //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
        val msg = WXMediaMessage(webpage)
        msg.title = title
        msg.description = desc

        val thumbBmp: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_launcher_wx)
        msg.thumbData = units(thumbBmp)

        //构造一个Req
        val req: SendMessageToWX.Req = SendMessageToWX.Req()
        req.transaction = buildTransaction("webpage")
        req.message = msg
        req.scene = scene

        //调用api接口，发送数据到微信
        api.sendReq(req)
    }

    private fun units(thumbBmp: Bitmap): ByteArray? {
        //Bitmap转换成byte[]
        val baos: ByteArrayOutputStream = ByteArrayOutputStream();
        thumbBmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();
    }

    private fun buildTransaction(type: String?): String? {
        return if (type == null) System.currentTimeMillis().toString() else type + System.currentTimeMillis()
    }

    private fun showImageList(
        mContext: Context,
        imageRecyclerView: RecyclerView,
        allList: ArrayList<TownshipBean.ShowFileListBean>?
    ) {
        if (allList != null && allList.size != 0) {
            imageRecyclerView.visibility = View.VISIBLE
            val mAlbumSelectedShowAdapter = ImageShowAdapter(mContext, allList)
            imageRecyclerView.layoutManager = GridLayoutManager(mContext, 4)
            imageRecyclerView.setHasFixedSize(true)
            imageRecyclerView.adapter = mAlbumSelectedShowAdapter
            mAlbumSelectedShowAdapter.setOnItemClickListener { _, position, fileBean ->
                if ("sp" == fileBean.fileType) {
                    if (XUtils.string().isNotEmpty(fileBean.imgUrl)) {
                        VideoPlaySingleActivity.start(this@OrgCountryDetailsActivity, VideoSourceEntity("视频信息", fileBean.imgUrl))
                    } else {
                        XUtils.toast().show("地址不可用")
                    }
                } else {
                    val imgList = ArrayList<String>()
                    for (item in allList) {
                        if ("sp" != item.fileType) {
                            imgList.add(item.imgUrl)
                        }
                    }
                    PhotoPreviewActivity.start(this@OrgCountryDetailsActivity, 0, imgList)
                }

            }
        } else {
            imageRecyclerView.visibility = View.GONE
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        townshipBean = intent.getSerializableExtra("communityBean") as TownshipBean

        if (townshipBean == null) {
            return
        }

        setViewTitle(XUtils.string().getNotNullValue(townshipBean!!.name), R.drawable.share_icon_black) {
            if (!LocalCache.getAutoLogin()) {
                // 登录检测
                XUtils.intent().openActivity(this, LoginActivity::class.java).start()
                return@setViewTitle
            }
            shareToWx(townshipBean!!)
        }

        initView()

        viewModel = OrgViewModel()
    }

    private fun initView() {
        titleNameTv.text = XUtils.string().getNotNullValue(townshipBean!!.name)
        addressTv.text = XUtils.string().getNotNullValue(townshipBean!!.address)

        if (XUtils.string().isNotEmpty(townshipBean!!.exhibitionCopy)) {
            exhibitionCopyTv.text = XUtils.string().getNotNullValue(townshipBean!!.exhibitionCopy)
            exhibitionCopyTv.visibility = View.VISIBLE
        } else {
            exhibitionCopyTv.visibility = View.GONE
        }

        if (XUtils.string().isNotEmpty(townshipBean!!.description)) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                descriptionTv.text = Html.fromHtml(XUtils.string().getNotNullValue(townshipBean!!.description), Html.FROM_HTML_MODE_LEGACY)
            } else {
                descriptionTv.text = Html.fromHtml(XUtils.string().getNotNullValue(townshipBean!!.description))
            }
//            descriptionTv.text = XUtils.string().getNotNullValue(townshipBean!!.description)
            descriptionTv.visibility = View.VISIBLE
        } else {
            descriptionTv.visibility = View.GONE
        }

        adminNameTv.text = "联系人：" + XUtils.string().getNotNullValue(townshipBean!!.inLeader)
        adminPhoneNumTv.text = "电话：" + XUtils.string().getNotNullValue(townshipBean!!.phone)

        bottomView.setOnClickListener {
            val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:${XUtils.string().getNotNullValue(townshipBean!!.phone)}"))
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
        }

        gotoBtn.setOnClickListener {

            if (townshipBean!!.lat != null && townshipBean!!.lng != null) {
                val lat = townshipBean!!.lat
                val lng = townshipBean!!.lng
                gotoNaviMap(XUtils.string().getNotNullValue(townshipBean!!.address), lng, lat)
            } else {
                XUtils.toast().show("导航信息不可用")
            }
        }

        if (townshipBean!!.showFileList == null || townshipBean!!.showFileList.size == 0) {
            imageRecyclerView.visibility = View.GONE
        } else {
//            val fileUrlList = ArrayList<String>()
//            for (fileBean in townshipBean!!.showFileList) {
//                fileUrlList.add(fileBean.imgUrl)
//            }

            if (townshipBean!!.showFileList.size > 0) {
                imageRecyclerView.visibility = View.VISIBLE
                showImageList(this, imageRecyclerView, townshipBean!!.showFileList)
            } else {
                imageRecyclerView.visibility = View.GONE
            }
        }

        // 位置纠偏
        if (XUtils.string().isNotEmpty(LocalCache.getLoginUserId()) &&
            XUtils.string().isNotEmpty(townshipBean!!.managerId) &&
            townshipBean!!.managerId == LocalCache.getLoginUserId()
        ) {
            freshLocationTv.setOnClickListener {
                XUtils.intent().openActivity(this@OrgCountryDetailsActivity, PoiSelectMapViewActivity::class.java)
                    .requestCode(CodeValue.MAP_SELECT_POI_CODE).start()
            }
            freshLocationTv.visibility = View.VISIBLE
        } else {
            freshLocationTv.visibility = View.GONE
        }
    }

    private fun showImg(fileUrlList: ArrayList<String>) {

        when (fileUrlList.size) {
            1 -> {
                img1.visibility = View.VISIBLE
                Glide.with(this).load(fileUrlList[0]).error(R.drawable.default_img).into(img1)
            }
            2 -> {
                img1.visibility = View.VISIBLE
                Glide.with(this).load(fileUrlList[0]).error(R.drawable.default_img).into(img1)

                img2.visibility = View.VISIBLE
                Glide.with(this).load(fileUrlList[1]).error(R.drawable.default_img).into(img2)
            }
            3 -> {
                img1.visibility = View.VISIBLE
                Glide.with(this).load(fileUrlList[0]).error(R.drawable.default_img).into(img1)

                img2.visibility = View.VISIBLE
                Glide.with(this).load(fileUrlList[1]).error(R.drawable.default_img).into(img2)

                img3.visibility = View.VISIBLE
                Glide.with(this).load(fileUrlList[2]).error(R.drawable.default_img).into(img3)
            }
            else -> {
                img1.visibility = View.VISIBLE
                Glide.with(this).load(fileUrlList[0]).error(R.drawable.default_img).into(img1)

                img2.visibility = View.VISIBLE
                Glide.with(this).load(fileUrlList[1]).error(R.drawable.default_img).into(img2)

                img3.visibility = View.VISIBLE
                Glide.with(this).load(fileUrlList[2]).error(R.drawable.default_img).into(img3)

                moreImgMore.visibility = View.VISIBLE
                Glide.with(this).load(fileUrlList[3]).error(R.drawable.default_img).into(moreImgMore)
//                moreImgMore
            }
        }
    }

    private fun gotoNaviMap(addressStr: String, lng: Double, lat: Double) {
        val hasAppPnList = PhoneUtil.hasInstalled(this, arrayOf("com.autonavi.minimap", "com.baidu.BaiduMap", "com.tencent.map"))

        when {
            hasAppPnList.size == 1 -> {
                when (hasAppPnList[0]) {
                    "com.autonavi.minimap" -> {
                        AMapNavi.openGaodeMap(this, addressStr, lng, lat, AMapNavi.DATA_FROM_GAODE)
                    }
                    "com.baidu.BaiduMap" -> {
                        AMapNavi.openBaiduMap(this, addressStr, lng, lat, AMapNavi.DATA_FROM_GAODE)
                    }
                    "com.tencent.map" -> {
                        AMapNavi.openTencentMap(this, addressStr, lng, lat, AMapNavi.DATA_FROM_GAODE)
                    }
                }
            }
            hasAppPnList.size > 1 -> {
                when (hasAppPnList[0]) {
                    "com.autonavi.minimap" -> {
                        AMapNavi.openGaodeMap(this, addressStr, lng, lat, AMapNavi.DATA_FROM_GAODE)
                    }
                    "com.baidu.BaiduMap" -> {
                        AMapNavi.openBaiduMap(this, addressStr, lng, lat, AMapNavi.DATA_FROM_GAODE)
                    }
                    "com.tencent.map" -> {
                        AMapNavi.openTencentMap(this, addressStr, lng, lat, AMapNavi.DATA_FROM_GAODE)
                    }
                }
            }
            else -> {
                XUtils.toast().show("手机需要高德、百度或腾讯地图App")
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == CodeValue.ResultCodeSuccess) {

            when (requestCode) {
                CodeValue.MAP_SELECT_POI_CODE -> {
                    if (data != null) {
                        lat = data.getDoubleExtra("latitude", 0.0)
                        lng = data.getDoubleExtra("longitude", 0.0)
                        address = data.getStringExtra("address") as String
                        updateTownInfo(lat, lng, address)
                    }
                }
            }
        }
    }

    var lat: Double = 0.0
    var lng: Double = 0.0
    var address: String = ""

    private fun updateTownInfo(lat: Double, lng: Double, address: String) {

        val vo = TownshipVo()
        vo.id = townshipBean!!.id
        vo.lat = lat.toString()
        vo.lng = lng.toString()
        vo.address = address

        showLoadingDialog("正在更新")
        Log.e("RxRetrofit", JSON.toJSONString(vo))
        viewModel!!.updateTownInfo(vo)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<String>) {
        if (result.eventType != "updateTownInfo") {
            return
        }

        hideLoadingDialog()

        when (result.code) {
            ResultInfo.SUCCESS -> {
                if (result.data != null) {
                    XUtils.toast().show("更新成功")
                    townshipBean!!.lat = lat
                    townshipBean!!.lng = lng
                    townshipBean!!.address = address
                    initView()
                } else {
                    XUtils.toast().show("查无结果")
                }
            }
            ResultInfo.TOKEN_OVERDUE -> {
            }
            else -> {
                XUtils.toast().show(result.msg)
            }
        }
    }
}